package com.bluesmart.mia;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.sys.Constants;
import com.sys.DemoApp;
import com.util.Constant;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Utils;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class NoteActivity extends BaseActivity implements OnClickListener{
	int mSelected = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_note);

		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);

		findViewById(R.id.img0).setOnClickListener(this);
		findViewById(R.id.img1).setOnClickListener(this);
		findViewById(R.id.img2).setOnClickListener(this);
		findViewById(R.id.img3).setOnClickListener(this);
		findViewById(R.id.img4).setOnClickListener(this);
		findViewById(R.id.img5).setOnClickListener(this);
		findViewById(R.id.img6).setOnClickListener(this);
		findViewById(R.id.img7).setOnClickListener(this);
		findViewById(R.id.img8).setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		if(arg0.getId() == R.id.left) finish();
		else if(arg0.getId() == R.id.right) sendHttpRequest();
		else 
		{
			mSelected = arg0.getId() - R.id.img0;
			showImagePicker();
		}
	}
	
	private void sendHttpRequest() {
		String text = ((EditText)findViewById(R.id.content)).getText().toString();
		if(text.length() == 0)
		{
			ToastUtil.showToastWithAlertPic(R.string.sign_in_tip);
			return;
		}
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {

				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000"))
				{
					if(mPhotoFile[0] == null)
					{
						List<Activity> list = ((DemoApp) getApplicationContext()).getActivityList();
						((NoteViewActivity)list.get(list.size() - 2)).sendChartHttpRequest(true);
						
						finish();
						ToastUtil.showToastWithAlertPic(R.string.success);
					}
					else
					{
						sendHttpImgRequest(ruser.getString("noteid"));
					}
				}
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("babyid", ((DemoApp)getApplicationContext()).getSeletedBaby().getString("babyid"));
		params.put("notetype", "" + getIntent().getExtras().getInt("type"));
		params.put("handtype", "add");
		params.put("content", text);

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/NoteHandler.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	private void sendHttpImgRequest(String noteid) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					List<Activity> list = ((DemoApp) getApplicationContext()).getActivityList();
					((NoteViewActivity)list.get(list.size() - 2)).sendChartHttpRequest(true);
					
					ToastUtil.showToastWithAlertPic(R.string.success);
					finish();
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else
				{
				}
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("handtype", "note");
		params.put("noteid", noteid);
		try {
			for(int i = 0; i < 9; i++)
			{
				if(mPhotoFile[i] != null)
				{
					params.put("filename" + i, mPhotoFile[i]);
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		MgqRestClient.post(Constant.SERVER_URL + "/sw/uploadimg.ashx", params, loginHandler);
	}
	
	void showImagePicker()
	{
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		
		OnClickListener listen = new OnClickListener()
		{
			@Override
			public void onClick(View arg0) {
				if(arg0.getId() == R.id.cancel) mDialog.dismiss();
				else if(arg0.getId() == R.id.pic)
				{
					mDialog.dismiss();
					Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
					getAlbum.setType("image/*");
					startActivityForResult(getAlbum, 3);
				}
				else if(arg0.getId() == R.id.camera)
				{
					mDialog.dismiss();
					startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), 4);
				}
				else
				{
					mDialog.dismiss();
					
					boolean showAdd = true;
					for(int i = mSelected; i < 8; i++)
					{
						mPhotoFile[i] = mPhotoFile[i + 1];
						if(mPhotoFile[i] != null)
						{
							((ImageView)findViewById(R.id.img0 + i)).setImageBitmap(mBitmap[i + 1]);
						}
						else
						{
							((ImageView)findViewById(R.id.img0 + i)).setImageResource(R.drawable.a41);
							if(!showAdd) 
							{
								findViewById(R.id.img0 + i).setVisibility(View.INVISIBLE);
							}
							showAdd = false;
						}
					}
					
					mPhotoFile[8] = null;
					mBitmap[8] = null;
					
					((ImageView)findViewById(R.id.img0 + 8)).setImageResource(R.drawable.a41);
					findViewById(R.id.img0 + 8).setVisibility(View.INVISIBLE);
				}
			}
		};

		mDialog.setContentView(R.layout.dialog_img_choose);
		mDialog.findViewById(R.id.camera).setOnClickListener(listen);
		mDialog.findViewById(R.id.pic).setOnClickListener(listen);
		mDialog.findViewById(R.id.cancel).setOnClickListener(listen);
		mDialog.findViewById(R.id.del).setOnClickListener(listen);
		if(mPhotoFile[mSelected] != null) mDialog.findViewById(R.id.del).setVisibility(View.VISIBLE);
		mDialog.show();
	}

	private File mPhotoFile[] = new File[9];
	private Bitmap mBitmap[] = new Bitmap[9];
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;
		
		Bitmap bitmap = null;
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 4) {
				Uri uri = data.getData();
				if (uri != null) {
					bitmap = BitmapFactory.decodeFile(uri.getPath());
				}

				if (bitmap == null) {
					Bundle bundle = data.getExtras();
					if (bundle != null) {
						bitmap = (Bitmap) bundle.get("data");
					}
				}
			} else if (requestCode == 3) {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				bitmap = Utils
						.getImageThumbnail(cursor.getString(column_index));
			}

			if (bitmap == null)
				return;
			
			mPhotoFile[mSelected] = new File("/mnt/sdcard/" + "jb_tmp" + mSelected + ".jpg");// 将要保存图片的路径
			mPhotoFile[mSelected].deleteOnExit();
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(mPhotoFile[mSelected]));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			mBitmap[mSelected] = bitmap;
			((ImageView)findViewById(R.id.img0 + mSelected)).setImageBitmap(mBitmap[mSelected]);
			if(mSelected < 8)
			{
				findViewById(R.id.img0 + mSelected + 1).setVisibility(View.VISIBLE);
			}
		}
	}
}
